package com.cgt.springboot.controller;

import com.cgt.springboot.pojo.Type;
import com.cgt.springboot.service.ITypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/type")
public class TypeController {
	@Autowired
	private ITypeService typeService;

	//1.使用Map实现缓存
	//缺点：1、在内存里面，重启就销毁  2、只能在单机下面有效，无法实现分布式环境下缓存
	//private Map<String, Object> map = new HashMap<>();
	private Map<String, List<Type>> map = new HashMap<>();

	@Autowired
	private RedisTemplate redisTemplate;

	@RequestMapping("/list")
	public List<Type> list() {
		//1.先检查reids缓存有没有数据
		List<Type> typeList = redisTemplate.opsForList().range("typeList", 0, -1);
		//2.redis里面没有数据
		if (CollectionUtils.isEmpty(typeList)) {
			//3.查询数据库
			typeList = typeService.list();
			//4.从数据库查询出来之后，更新到redis缓存里面
			redisTemplate.opsForList().rightPushAll("typeList", typeList);
		}
		return typeList;
	}

	@RequestMapping("/list1")
	public List<Type> list1() {
		//1.先检查map缓存有没有数据
		List<Type> typeList = map.get("typeList");
		//2.map里面没有数据
		//CollectionUtils.isEmpty  集合的空
		//ObjectUtils.isEmpty      单个对象
		if (CollectionUtils.isEmpty(typeList)) {
			//3.查询数据库
			typeList = typeService.list();
			//4.从数据库查询出来之后，更新到map缓存里面
			map.put("typeList", typeList);
		}
		return typeList;
	}

}
